#include<pthread.h>
#include<semaphore.h>
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>

sem_t sem_P;     //全局定义信号量sem
sem_t sem_V;     //全局定义信号量sem

void* pthread_fun0(void *arg)
{
    //对信号量sem_P执行P操作
    sem_wait(&sem_P);
    char *str = "hello ";
    while(*str != '\0')
    {
        putchar(*str++);
        sleep(1);
        fflush(stdout);
    }
    //对信号量sem_V执行V操作
    sem_post(&sem_V);
    pthread_exit(NULL);
}

void* pthread_fun1(void *arg)
{
    //对信号量sem_V执行P操作
    sem_wait(&sem_V);
    char *str = "world";
    while(*str != '\0')
    {
        putchar(*str++);
        sleep(1);
        fflush(stdout);
    }
    //对信号量sem_P执行V操作
    sem_post(&sem_P);
    pthread_exit(NULL);
}

int main()
{
    //初始化信号量
    sem_init(&sem_P,0,1);
    sem_init(&sem_V,0,0);

    printf("进程执行中...\n");
    pthread_t id[2];
    pthread_create(&id[0],NULL,pthread_fun0,NULL);
    pthread_create(&id[1],NULL,pthread_fun1,NULL);

    pthread_join(id[0],NULL);
    pthread_join(id[1],NULL);
    printf("\n");

    //销毁信号量
    sem_destroy(&sem_P);
    sem_destroy(&sem_V);
    printf("进程退出\n");
    return 0;
}